/**
 * @license
 * Copyright 2021 Du Tian Wei
 * SPDX-License-Identifier: Apache-2.0
 */
import Template from '../jsruntime/developtools/template.mjs';
import IframeSimulator from '../iframeconnector/IframeSimulator.mjs';
// import ToPython from '../jsruntime/developtools/python/ToPython.mjs'
import ToC from '../jsruntime/developtools/c/ToC.mjs';
// import OpenBrotherSerialProtocol from './openBrotherSerialProtocol.mjs';
import BitmapFonts from '../frontpage/components/bitmapFonts/bitmapFonts.mjs';
import UIBuilder from '../frontpage/components/UIBuilder/UIBuilder.mjs';
import SceneManager from '../frontpage/core/ub/SceneManager.mjs';
import '../frontpage/js/htmls/SceneManager/SceneManager.mjs';
import DebugController from '../frontpage/js/htmls/debugger/DebugSider.mjs';
export default async function () {
    DebugController.installSider();
    DebugController.installContextMenu();
    await OpenBlock.Utils.loadJSAsync([
        // '../../js/htmls/SceneManager/SceneManager.mjs',
        "../jsruntime/test/env/native-web3d.js",
        "../jsruntime/test/env/i18n_zh.js",
        "../jsruntime/test/env/native.js"]);
    let openBrotherTemplate = await axios.get('../static/openBrother.template.py');
    openBrotherTemplate = Template.parseTemplate(openBrotherTemplate.data, '#');
    let simulator = new IframeSimulator();
    let simulator3D = new IframeSimulator('../jsruntime/web3d/index.html');
    let scenes = [
        {
            name: 'web',
            env: 'web',
            beforeCreate(scene) {
                console.log('beforeCreate', scene);
                return scene;
            },
            beforeUpdate(scene) {
                console.log('beforeUpdate', scene);
                return scene;
            },
            runMethods: [
                {
                    icon: 'ios-play',
                    name: OB_IDE.$t('运行'),
                    async run(scene) {
                        await OB_IDE.saveAllTabs();
                        OpenBlock.exportExePackage(scene, (e, buf) => {
                            if (e) {
                                OB_IDE.$Message.error(OB_IDE.$t('编译失败'));
                            } else {
                                simulator.runProject(buf, scene);
                            }
                        });
                    }
                },
                {
                    icon: 'md-bug',
                    name: OB_IDE.$t('调试'),
                    async run(scene) {
                        await OB_IDE.saveAllTabs();
                        OpenBlock.exportExePackage(scene, (e, buf) => {
                            if (e) {
                                showCompileError(e);
                            } else {
                                let breakpoints = DebugController.getBreakPointsBySceneForDebugger(scene);
                                simulator.debugProject(buf, scene, null, breakpoints);
                            }
                        }, { debug: true });
                    }
                },
                {
                    icon: 'ios-apps',
                    name: OB_IDE.$t('新运行'),
                    async run(scene) {
                        await OB_IDE.saveAllTabs();
                        OpenBlock.exportExePackage(scene, (e, buf) => {
                            if (e) {
                                OB_IDE.$Message.error(OB_IDE.$t('编译失败'));
                            } else {
                                simulator.newWindow(buf, scene);
                            }
                        });
                    }
                },
                {
                    icon: 'ios-browsers',
                    name: OB_IDE.$t('独立窗口运行'),
                    async run(scene) {
                        await OB_IDE.saveAllTabs();
                        OpenBlock.exportExePackage(scene, (e, buf) => {
                            if (e) {
                                OB_IDE.$Message.error(OB_IDE.$t('编译失败'));
                            } else {
                                simulator.standaloneWindow(buf, scene);
                            }
                        });
                    }
                },
                // {
                //     icon: 'ios-code-download',
                //     name: OB_IDE.$t('导出字节码'),
                //     async run(scene) {
                //         await OB_IDE.saveAllTabs();
                //         OpenBlock.exportExePackage(scene, (e, buf) => {
                //             if (e) {
                //                 OB_IDE.$Message.error(OB_IDE.$t('编译失败'));
                //             } else {
                //                 FileOD.Save(scene.name + '.web.xe', new Blob([buf]));
                //             }
                //         });
                //     }
                // },
            ]
        },
        {
            name: "editorExt",
            env: "editorExt",
            runMethods: [
                // {
                //     icon: 'ios-code-download',
                //     name: OB_IDE.$t('导出字节码'),
                //     run(scene) {
                //         OpenBlock.saveAllSrc();
                //         OpenBlock.exportExePackage(scene, (e, buf) => {
                //             if (e) {
                //                 OB_IDE.$Message.error(OB_IDE.$t('编译失败'));
                //             }
                //             FileOD.Save(scene.name + '.editorExt.xe', new Blob([buf]));
                //         });
                //     }
                // },
            ]
        },
        {
            name: 'VUE',
            env: 'VUE',
            beforeCreate(scene) {
                console.log('beforeCreate', scene);
                return scene;
            },
            beforeUpdate(scene) {
                console.log('beforeUpdate', scene);
                return scene;
            },
            runMethods: [{
                icon: 'md-brush',
                name: OB_IDE.$t('UI设计'),
                showName: true,
                async run(scene) {
                    UIBuilder.open(scene);
                }
            }]
        },
        {
            name: 'web3d',
            env: 'web3d',
            beforeCreate(scene) {
                console.log('beforeCreate', scene);
                return scene;
            },
            beforeUpdate(scene) {
                console.log('beforeUpdate', scene);
                return scene;
            },
            runMethods: [
                {
                    icon: 'ios-play',
                    name: OB_IDE.$t('运行'),
                    async run(scene) {
                        await OB_IDE.saveAllTabs();
                        OpenBlock.exportExePackage(scene, (e, buf) => {
                            if (e) {
                                OB_IDE.$Message.error(OB_IDE.$t('编译失败'));
                            } else {
                                simulator3D.runProject(buf, scene);
                            }
                        });
                    }
                },
                {
                    icon: 'ios-apps',
                    name: OB_IDE.$t('新运行'),
                    async run(scene) {
                        await OB_IDE.saveAllTabs();
                        OpenBlock.exportExePackage(scene, (e, buf) => {
                            if (e) {
                                OB_IDE.$Message.error(OB_IDE.$t('编译失败'));
                            } else {
                                simulator3D.newWindow(buf, scene);
                            }
                        });
                    }
                },
                {
                    icon: 'ios-browsers',
                    name: OB_IDE.$t('独立窗口运行'),
                    async run(scene) {
                        await OB_IDE.saveAllTabs();
                        OpenBlock.exportExePackage(scene, (e, buf) => {
                            if (e) {
                                OB_IDE.$Message.error(OB_IDE.$t('编译失败'));
                            } else {
                                simulator3D.standaloneWindow(buf, scene);
                            }
                        });
                    }
                },
                // {
                //     icon: 'ios-code-download',
                //     name: OB_IDE.$t('导出字节码'),
                //     async run(scene) {
                //         await OB_IDE.saveAllTabs();
                //         OpenBlock.exportExePackage(scene, (e, buf) => {
                //             if (e) {
                //                 OB_IDE.$Message.error(OB_IDE.$t('编译失败'));
                //             } else {
                //                 FileOD.Save(scene.name + '.web.xe', new Blob([buf]));
                //             }
                //         });
                //     }
                // },
            ]
        },
    ];
    try {
        await (import("../../env-static-resources/forWS63E/editor/burntool.mjs").then(async (burntool) => {
            await OpenBlock.Utils.loadJSAsync([
                "../../env-static-resources/forWS63E/editor/ws63flash.js",
                "../../env-static-resources/forWS63E/v1/nativeExt_ws63e.js",
                "../../env-static-resources/forWS63E/v1/nativeExt_ws63e-iotVar.js"
            ]);
            let c_start = await (await fetch('/env-static-resources/forWS63E/v1/ws63e.template.start.c')).text();
            let c_end = await (await fetch('/env-static-resources/forWS63E/v1/ws63e.template.end.c')).text();

            async function buildTemplate(scene) {
                let template = {
                    extInclude: c_start.replace('BITMAP_FUNCTION', await BitmapFonts.toC(scene)),
                    startVM: c_end,
                }
                return template;
            }
            async function addNetworkInfoToC(scene, c) {
                if (window.remoteProject?.remotProjId) {
                    return `
    #define SCENE_ID "${scene.id}"
    #define PROJECT_ID "${remoteProject.remotProjId}"
    `
                        + c;
                } else {
                    return c;
                }
            }
            scenes.push({
                name: "WS36E",
                env: "WS63E_V1",
                runMethods: [
                    {
                        icon: "ios-keypad",
                        name: OB_IDE.$t('点阵管理'),
                        run(scene) {
                            BitmapFonts.openSettings(
                                {
                                    colors: [{ r: 0, g: 0, b: 0 }, { r: 4, g: 224, b: 253 }],
                                    width: 128, height: 64
                                });
                        }
                    },
                    {
                        icon: "md-game-controller-b",
                        name: OB_IDE.$t('下载C代码'),
                        async run(scene) {
                            let template = await buildTemplate(scene);
                            let c = await ToC.buildLogicSrc({
                                env: scene.env,
                                srcList: scene.srcList,
                                entry: scene.entry,
                                partials: template
                            });
                            c = await addNetworkInfoToC(scene, c);
                            FileOD.Save(scene.name + '.WS63E.c', c);
                        }
                    },
                    {
                        icon: "ios-barcode",
                        name: OB_IDE.$t('编译下载固件'),
                        async run(scene) {
                            let template = await buildTemplate(scene);
                            let file = await getBinImage(scene, 'blob', 'ws63-liteos', template, 'roarlang.c');
                            if (file) {
                                FileOD.Save(scene.name + '.ws63-liteos.fwpkg', file);
                            }
                        }
                    },
                    {
                        icon: "ios-bonfire",
                        name: OB_IDE.$t('编译烧录固件'),
                        async run(scene) {
                            let template = await buildTemplate(scene);
                            let file = await getBinImage(scene, 'arraybuffer', 'ws63-liteos', template, 'roarlang.c');
                            if (file) {
                                await (new burntool.BurnTool()).burn(file, scene);
                            }
                        }
                    }
                ]
            });
        }).finally(() => {
        }));
    } catch (e) {
        console.warn(e);
    }
    for (let i in scenes) {
        let s = scenes[i];
        if (!OpenBlock.Env.hasEnv(s.env)) {
            OpenBlock.Env.addNewEnv(s.env);
        }
        SceneManager.addAvailableScene(s);
    }

    OpenBlock.Utils.handleUrlHash(() => {
        OB_IDE.$Message.info(OB_IDE.$t('正在打开工程，请稍后'));
        simulator.loading = true;
        showOverallLoading();
    }, async (error, loaded) => {
        if (!loaded) {
            await new Promise((resolve, reject) => {
                axios.get('../defaultproject.obp', {
                    responseType: 'arraybuffer', // default
                }).then(({ data }) => {
                    OpenBlock.importProjectZip(data, resolve);
                }).catch((e) => {
                    console.log(e);
                    resolve();
                });
            });
        }
        await OpenBlock.Version.updateVersion();
        await OpenBlock.compileAllSrc();
        simulator.loading = false;
        hideOverallLoading();
        OB_IDE.$Message.success(OB_IDE.$t('工程加载完成'));
    });
    BitmapFonts.install();
}